using System;
using System.Collections.Generic;
using Edge.Common;
using Edge.Common.ComponentModel.Notification;
using Edge.Common.Services;
using Edge.Common.Utils;
using Edge.DAL.Common;
using Edge.DAL.Managers;
using NHibernate;
using NHibernate.Expression;
using NHibernate.Type;
using Shop.Business.Domain.Customers;
using Shop.Business.Domain.Orders;
using Order = Shop.Business.Domain.Orders.Order;

namespace Shop.DAL.Managers
{
    class OrderItemManager : AbstractManager<OrderItem, int, Customer>, IOrderItemManager
    {
        public ICollection<OrderItem> Find(FetchOptions fetchOptions, OrderItemFilter filter)
        {
            ICriteria criteria = CreateCriteria(fetchOptions);
            AddRestrictions(criteria, filter);
            return criteria.List<OrderItem>();
        }

        public int Count(OrderItemFilter filter)
        {
            ICriteria criteria = CreateCriteria();
            AddRestrictions(criteria, filter);
            criteria.SetProjection(Projections.RowCount());
            return (int)criteria.List()[0];
        }


        private void AddRestrictions(ICriteria criteria, OrderItemFilter filter)
        {
            if (!StringUtils.IsBlankOrNull(filter.GetText()) && !(filter.GetText().Trim().Equals("")))
            {
                criteria.Add(Expression.Disjunction()
                                 .Add(Expression.Like("FirstName", "%" + filter.GetText().Trim() + "%"))
                                 .Add(Expression.Like("LastName", "%" + filter.GetText().Trim() + "%"))
                    );
            }
        }

        public void ChangeOrderofItem(OrderItem orderItem, Order order)
        {
            using (IDalOperation op = CreateLoadOperation())
            {
                IQuery query = Session.GetNamedQuery("ChangeOrderofItem");
                query.SetParameter("id", orderItem.Id, TypeFactory.Basic("int"));
                query.SetParameter("orderId", order.Id, TypeFactory.Basic("int"));
                query.UniqueResult();
                op.Commit();
            }
        }


    }
}